namespace SimpleWebServices.Web.UI.Html
{
    using System;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;
    using SimpleWebServices;
    using SimpleWebServices.Web.UI.Html.Elements;

    [XmlRoot("anchors")]
    public sealed class AnchorCollection : Collection<Anchor>, IXmlSerializable
    {
        public Anchor this[string id]
        {
            get
            {
                return this.Where(x => string.Equals(id, x.Id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            }
        }

        public bool Contains(string id)
        {
            return null != this[id];
        }

        XmlSchema IXmlSerializable.GetSchema()
        {
            throw new NotSupportedException();
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (null == reader)
            {
                throw new ArgumentNullException("reader");
            }

            if (reader.IsEmptyElement)
            {
                reader.Read();
            }
            else
            {
                string name = reader.Name;
                while (true)
                {
                    if (XmlNodeType.EndElement == reader.NodeType && reader.Name == name)
                    {
                        reader.Read();
                        break;
                    }
                    else if ("a".Equals(reader.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        this.Add(reader.ReadOuterXml().Deserialize<Anchor>());
                    }
                    else
                    {
                        reader.Read();
                    }
                }
            }
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            if (null == writer)
            {
                throw new ArgumentNullException("writer");
            }

            foreach (Anchor item in this)
            {
                writer.WriteRaw(item.Serialize().CreateNavigator().OuterXml);
            }
        }
    }
}